package handler

import (
	"context"
	"github.com/astaxie/beego/logs"
	"github.com/astaxie/beego/orm"
	"github.com/garyburd/redigo/redis"
	"ihome/models"
	"ihome/utils"
	"path"

	"github.com/micro/go-micro/util/log"

	uploadAvatar "ihome/proto/uploadAvatar"
)

type UploadAvatar struct{}

// Call is a single request handler called via client.Call or the generated client code
func (e *UploadAvatar) SrvUploadAvatar(ctx context.Context, req *uploadAvatar.Request, rsp *uploadAvatar.Response) error {
	logs.Info("上传用户头像 UploadAvatar /api/v1.0/user/avatar")

	rsp.Code = utils.RecodeOk
	rsp.Msg = utils.RecodeText(rsp.Code)

	size := len(req.Avatar)
	if req.FileSize != int64(size) {
		logs.Info("图片长度错误")
		rsp.Code = utils.RecodeDataerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	ext := path.Ext(req.FileExt)

	fileId, err := utils.UploadByBuffer(req.Avatar, ext[1:])
	if err != nil {
		logs.Info("上传失败", err)
		rsp.Code = utils.RecodeDataerr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	logs.Info("文件上传成功:", fileId)

	bm, err := utils.NewCache()
	if err != nil {
		logs.Info("redis连接失败", err)
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}
	sessionId := req.SessionId
	userIdObj := bm.Get(sessionId + "user_id")
	userId, _ := redis.Int(userIdObj, nil)

	user := models.User{Id: userId, Avatar_url: fileId}
	o := orm.NewOrm()
	_, err = o.Update(&user, "avatar_url")

	if err != nil {
		logs.Info("数据更新失败")
		rsp.Code = utils.RecodeDberr
		rsp.Msg = utils.RecodeText(rsp.Code)
		return nil
	}

	rsp.AvatarUrl = fileId

	return nil
}

// Stream is a server side stream handler called via client.Stream or the generated client code
func (e *UploadAvatar) Stream(ctx context.Context, req *uploadAvatar.StreamingRequest, stream uploadAvatar.UploadAvatar_StreamStream) error {
	log.Logf("Received UploadAvatar.Stream request with count: %d", req.Count)

	for i := 0; i < int(req.Count); i++ {
		log.Logf("Responding: %d", i)
		if err := stream.Send(&uploadAvatar.StreamingResponse{
			Count: int64(i),
		}); err != nil {
			return err
		}
	}

	return nil
}

// PingPong is a bidirectional stream handler called via client.Stream or the generated client code
func (e *UploadAvatar) PingPong(ctx context.Context, stream uploadAvatar.UploadAvatar_PingPongStream) error {
	for {
		req, err := stream.Recv()
		if err != nil {
			return err
		}
		log.Logf("Got ping %v", req.Stroke)
		if err := stream.Send(&uploadAvatar.Pong{Stroke: req.Stroke}); err != nil {
			return err
		}
	}
}
